package Network

import (
	"SQL/FSDB"
	"database/sql"
)

type GroupSessionRow struct {
	GroupID      string `json:"GroupID"`
	GroupName    string `json:"GroupName"`
	GroupIconURL string `json:"GroupIconURL"`
	SenderID     string `json:"SenderID"`
	SenderName   string `json:"SenderName"`
	MsgID        string `json:"MsgID"`
	MsgType      string `json:"MsgType"`
	Msg          string `json:"Msg"`
	CreateTime   string `json:"CreateTime"`
	UnreadNum    int    `json:"UnreadNum"`
}

func groupSessionInContext(tx *sql.Tx, userID string) (errCode int, errMsg string, list interface{}) {

	getGroupSessionSQL := `SELECT * FROM getGroupSession($1);`
	ggsStmt, ggsRows, err := FSDB.QueryTx(tx, getGroupSessionSQL, userID)
	if err != nil {
		return errEndTx, "getFriendSessionSQL tx.QueryTx 执行错误：" + err.Error(), nil
	}
	defer ggsStmt.Close()
	defer ggsRows.Close()

	sessionRows := make([]GroupSessionRow, 0)

	var (
		groupID      string
		groupName    string
		groupIconURL string
		senderID     string
		senderName   string
		msgID        string
		msgType      string
		msg          string
		createTime   string
		unreadNum    int
	)

	for ggsRows.Next() {
		err = ggsRows.Scan(&groupID, &groupName, &groupIconURL, &senderID, &senderName, &msgID, &msgType, &msg, &createTime, &unreadNum)
		if err != nil {
			return errEndTx, "gfsRows.Scan 执行错误：" + err.Error(), nil
		}
		sessionRow := GroupSessionRow{
			GroupID:      groupID,
			GroupName:    groupName,
			GroupIconURL: groupIconURL,
			SenderID:     senderID,
			SenderName:   senderName,
			MsgID:        msgID,
			MsgType:      msgType,
			Msg:          msg,
			CreateTime:   createTime,
			UnreadNum:    unreadNum,
		}
		sessionRows = append(sessionRows, sessionRow)
	}

	return Success, "成功获取 " + userID + " 的会话列表！", sessionRows
}
